var mode_type = null;
var check_type = null;
var allpro = null;
var pBName = null;
var pBState = null;
var pguid = null;
var userall = null;
$(function () {
    $.when(
        getuserall(),
        getdatadictionary("mode_type"),
        getdatadictionary("check_type"),
        $.get(baseURL + "csg/cpbase/select?ourid=isok", function(r) {
            allpro = r.returnlist;
            vm.allpro=allpro;
        })
    ).done(

        $("#jqGrid1").jqGrid({
            url: baseURL +'csg/cpbase/list?state=isdelno&ourid=isok',
            datatype: "json",
            colModel: [
                { label: 'guid', name: 'guid', index: 'guid', width: 50, key: true,hidden: true  },

                { label: '项目名称', name: 'pBName', index: 'p_b_name', width: 200 },
                { label: '参与人', name: 'pBCollectid', index: 'p_b_collectid', width: 150 ,
                    formatter: function (cellvalue, options, rowObject) {
                        var names = "";


                        var ss = (cellvalue.replace(/\"/g, "").replace("[", "").replace("]", "") + "").split(",");
                        for (var i = 0; i < ss.length; i++) {

                            for (d in userall) {
                                if (ss[i] == userall[d].userId + "") {

                                    names += userall[d].username + ",";
                                }
                            }
                        }
                        if (names.length > 0) {
                            names = names.substring(0, names.length - 1);
                        }
                        return names;
                    }
                },

                { label: '创建时间', name: 'pBAddtime', index: 'p_b_addtime', width: 150,
                    formatter:function(value,options,row){
                        return value!=null?new Date(value).Format('yyyy-MM-dd hh:mm'):"";}
                }
            ],
            viewrecords: true,
            height: 500,

            rowNum: 10,
            rowList : [10,30,50],
            rownumbers: true,
            rownumWidth: 25,
            autowidth:true,
            multiselect: true,
            pager: "#jqGridPager1",
            jsonReader : {
                root: "page.list",
                page: "page.currPage",
                total: "page.totalPage",
                records: "page.totalCount"
            },
            prmNames : {
                page:"page",
                rows:"limit",
                order: "order"
            },
            gridComplete:function(){
                //隐藏grid底部滚动条
                $("#jqGrid1").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
            }
        }),

        $("#jqGrid").jqGrid({
            //后台已有限制条件
            url: baseURL + 'csg/cmiddlecheck/list',
            datatype: "json",
            colModel: [
                { label: 'guid', name: 'guid', index: 'guid', width: 50, key: true,hidden:true },
                { label: '项目名称', name: 'pGuid', index: 'p_guid', width: 80,hidden:true,
                    formatter: function (cellvalue, options, rowObject) {
                        for (d in allpro) {
                            if (cellvalue == allpro[d].guid) return allpro[d].pBName;
                        }
                    }
                },
                { label: '经度', name: 'mCLongitude', index: 'm_c_longitude', width: 80,hidden:true },
                { label: '纬度', name: 'mCLatitude', index: 'm_c_latitude', width: 80,hidden:true },
                { label: '记录方式', name: 'mCMode', index: 'm_c_mode', width: 80,
                    formatter: function (cellvalue, options, rowObject) {
                        for (d in mode_type) {
                            if (cellvalue == mode_type[d].dKey) return mode_type[d].dValue;
                        }
                    }
                },
                { label: '记录类别', name: 'mCType', index: 'm_c_type', width: 80,
                    formatter: function (cellvalue, options, rowObject) {
                        for (d in check_type) {
                            if (cellvalue == check_type[d].dKey) return check_type[d].dValue;
                        }
                    }
                },
                { label: '编号/名称', name: 'mCName', index: 'm_c_name', width: 80 },
                { label: '电杆高度', name: 'mCHigh', index: 'm_c_high', width: 80 },
                { label: '检查日期', name: 'mCTime', index: 'm_c_time', width: 80 ,
                    formatter:function(value,options,row){
                        return value!=null?new Date(value).Format('yyyy-MM-dd'):"";}
                },
                { label: '审核结果', name: 'mCResult', index: 'm_c_result', width: 80 },
                { label: '采集人', name: 'mCUsername', index: 'm_c_username', width: 80 },
                { label: '采集人ID', name: 'mCUser', index: 'm_c_user', width: 80,hidden:true },
                { label: '数据状态', name: 'mCDatastate', index: 'm_c_datastate', width: 80,hidden:true },
                { label: '操作', name: '', width: 200, formatter: function (cellvalue, options, rowObject) {
                    return "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='showCmiddleInfo(\"" + rowObject.guid + "\")' >&nbsp;查看信息</a>"
                        +  "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='exportsCground(\"" + rowObject.guid + "\")' >&nbsp;导出接地体</a>"
                    // +  "&nbsp;&nbsp;<a  class='btn btn-primary' onclick='exportsimg(\"" + rowObject.guid + "\")' >&nbsp;导出照片</a>"
                }
                }
            ],
            viewrecords: true,
            height: 385,
            rowNum: 10,
            rowList : [10,30,50],
            rownumbers: true,
            rownumWidth: 25,
            autowidth:true,
            multiselect: true,
            pager: "#jqGridPager",
            jsonReader : {
                root: "page.list",
                page: "page.currPage",
                total: "page.totalPage",
                records: "page.totalCount"
            },
            prmNames : {
                page:"page",
                rows:"limit",
                order: "order"
            },
            gridComplete:function(){
                //隐藏grid底部滚动条
                $("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
            }
        })
    )
});

function showCmiddleInfo(guid) {
    var title ="隐蔽工程信息";
    var pGuid = vm.q.pGuid;//获取当前隐蔽工程所属的项目ID

    var content = "concealment.html?guid=" + guid+"&pGuid="+pGuid;
    layer.open({
        type: 2,
        title: title,
        shadeClose: true,
        shade: 0.5,
        maxmin: true, //开启最大化最小化按钮
        area: ['95%', '95%'],
        content: content

    });
}
function  getuserall()
{
    $.get(baseURL + "sys/user/select" , function (r) {
        userall = r.returnlist;

    });
    vm.userall=userall;

}

/**
 *  导出接地体
 * @param guid
 */
function exportsCground(guid) {
    location.href=baseURL + "csg/cmiddlecheck/exportsCground?guid="+guid;
}
/**
 *  导出检查照片
 */
function exportCmiddleImg() {
    var pGuid = vm.q.pGuid;
    var re_records = $("#jqGrid").jqGrid('getGridParam', 'records'); //获取数据总条数
    if (pGuid == null){
        alert("请选择项目");
        return;
    }
    if(re_records==0){
        alert("该项目无数据，请核对后操作");
        return;
    }
    location.href=baseURL + "csg/cmiddlecheck/exportsimg?pGuid="+pGuid;
}
/**
 *  导出检查详情
 */
function exportCmiddlecheck() {

    var pGuid = vm.q.pGuid;
    var re_records = $("#jqGrid").jqGrid('getGridParam', 'records'); //获取数据总条数
    if (pGuid == null){
        alert("请选择项目");
        return;
    }
    if(re_records==0){
        alert("该项目无数据，请核对后操作");
        return;
    }
    location.href=baseURL + "csg/cmiddlecheck/exports?pGuid="+pGuid;
}


/**
 *  数据字典
 * @param sss
 */
function getdatadictionary(sss)
{

    $.get(baseURL + "api/bdatadictionary/select?d_code="+sss, function(r){
        if(sss=="mode_type")
        {
            mode_type=r.returnlist;
        }
        if(sss=="check_type")
        {
            check_type=r.returnlist;
        }

        vm.mode_type=mode_type;
        vm.check_type=check_type;

    });
}


var vm = new Vue({
    el:'#rrapp',
    data:{
        showList: true,
        title: null,
        userall:userall,
        q:{
            // pBName:null,
            pGuid:null,
            mCname:null,
            psname:null,
            ppppBName:null,
            // pBState:null,
            mCType:null,
            mCMode:null
        },
        mode_type:mode_type,
        allpro:allpro,
        check_type:check_type,
        cMiddleCheck: {}
    },
    methods: {
        query: function () {
            vm.reload();
        },

        add: function(){
            vm.showList = false;
            vm.title = "新增";
            vm.mode_type=mode_type;
            vm.check_type=check_type;
            vm.cMiddleCheck = {};
        },
        update: function (event) {
            var guid = getSelectedRow();
            if(guid == null){
                return ;
            }

            var rowData = $("#jqGrid").jqGrid('getRowData',guid);
            var pname = rowData.pGuid;
            $.get(baseURL + "csg/cpbase/select?pname="+pname, function(r) {
                pguid=r.returnlist[0].guid;

                $.get(baseURL + "csg/cpbase/info/"+pguid, function(r) {
                    if (r.cPBase.pBState == 30) {
                        alert("项目已归档，无法修改检查信息！");
                    }else{
                        vm.showList = false;
                        vm.title = "修改";
                        vm.mode_type=mode_type;
                        vm.check_type=check_type;
                        vm.getInfo(guid)
                    }
                });

            });


        },
        saveOrUpdate: function (event) {

            var url = vm.cMiddleCheck.guid == null ? "csg/cmiddlecheck/save" : "csg/cmiddlecheck/update";
            $.ajax({
                type: "POST",
                url: baseURL + url,
                contentType: "application/json",
                data: JSON.stringify(vm.cMiddleCheck),
                success: function(r){
                    if(r.code === 0){
                        alert('操作成功', function(index){
                            vm.reload();
                            console.log("middle===刷新成功！")
                            // location.reload();
                        });
                    }else{
                        alert(r.msg);
                    }
                }
            });
        },
        del: function (event) {
            var guids = getSelectedRows();
            if(guids == null){
                return ;
            }

            var rowData = $("#jqGrid").jqGrid('getRowData',guids);
            var pname = rowData.pGuid;
            $.get(baseURL + "csg/cpbase/select?pname="+pname, function(r) {
                pguid=r.returnlist[0].guid;

                $.get(baseURL + "csg/cpbase/info/"+pguid, function(r) {
                    if (r.cPBase.pBState != 30) {
                        confirm('确定要删除选中的记录？', function(){
                            $.ajax({
                                type: "POST",
                                url: baseURL + "csg/cmiddlecheck/delete",
                                contentType: "application/json",
                                data: JSON.stringify(guids),
                                success: function(r){
                                    if(r.code == 0){
                                        alert('操作成功', function(index){
                                            $("#jqGrid").trigger("reloadGrid");
                                        });
                                    }else{
                                        alert(r.msg);
                                    }
                                }
                            });
                        });
                    }else{
                        alert("项目已归档，无法删除检查信息！")
                    }
                })
            });


        },
        getInfo: function(guid){
            $.get(baseURL + "csg/cmiddlecheck/info/"+guid, function(r){
                vm.cMiddleCheck = r.cMiddleCheck;
                vm.cMiddleCheck.mCTime = r.cMiddleCheck.mCTime!=null?new Date().Format("yyyy-MM-dd"):"";
            });
        },
        showprolist:function (event) {

            // vm.q.pGuid='b6400318-7a6f-4de5-92e8-ddec55f10394';
            layer.open({
                type: 1,
                offset: '50px',
                skin: 'layui-layer-molv',
                title: "选择项目",
                area: ['700px', '460px'],
                shade: 0,
                shadeClose: false,
                content: jQuery("#deptLayermy"),
                btn: ['确定', '取消'],
                btn1: function (index) {
                    var grid = $("#jqGrid1");
                    var rowKey = grid.getGridParam("selrow");
                    if (!rowKey) {
                        alert("请选择一条记录");
                        return;
                    }

                    var selectedIDs = grid.getGridParam("selarrrow");
                    if (selectedIDs.length > 1) {
                        alert("只能选择一条记录");
                        return;
                    }
                    // vm.getBasic(selectedIDs[0]);
                    vm.q.pGuid=selectedIDs[0];

                    for (d in  allpro) {
                        if (allpro[d].guid == selectedIDs[0]) {
                            vm.q.psname=allpro[d].pBName;
                        }
                    }
                    layer.close(index);

                }
            });


        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam','page');
            $("#jqGrid").jqGrid('setGridParam',{
                postData:{
                    // 'pBName':vm.q.pBName,
                    'mCname':vm.q.mCname,
                    "pGuid":vm.q.pGuid,
                    "mCType":vm.q.mCType,
                    "mCMode":vm.q.mCMode
                },
                page:page
            }).trigger("reloadGrid");
        },
        reloadpro: function (event) {

            console.log("a_______");
            var page = $("#jqGrid1").jqGrid('getGridParam','page');
            $("#jqGrid1").jqGrid('setGridParam',{
                postData:{
                    'pBName': vm.q.ppppBName,
                },
                page:page
            }).trigger("reloadGrid");
        }
    }
});